﻿using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using Bookvar.ObjectModel;

namespace Bookvar.UI
{
    public class ResourceItem : ListBoxItem
    {
        public ResourceItem()
        {
            ContentTemplateSelector = new ResourceItemTemplateSelector();
            Style = FindResource( new ComponentResourceKey( typeof( ResourceItem ), "ResourceItemStyleKey" ) ) as Style; 
        }

        public Resource Resource
        {
            get
            {
                return Content as Resource;
            }
            set
            {
                Content = value;
            }
        }
        
        private class ResourceItemTemplateSelector : DataTemplateSelector
        {
            public override DataTemplate SelectTemplate( object item, DependencyObject container )
            {
                Resource resource = item as Resource;
                string templateName = null;
                if ( resource != null )
                {
                    switch (resource.ResourceType)
                    {
                        case ResourceType.Icon:
                        {
                            templateName = "IconResourceItem";
                            break;
                        }
                        case ResourceType.Image:
                        {
                            templateName = "ImageResourceItem";
                            break;
                        }
                        case ResourceType.Video:
                        {
                            templateName = "VideoResourceItem";
                            break;
                        }
                        default:
                        {
                            Debug.Assert( false );
                            break;
                        }
                    }
                }
                if ( !string.IsNullOrEmpty( templateName ) )
                {
                    return ( (FrameworkElement) container ).FindResource(
                               new ComponentResourceKey( typeof( ResourceItem ), templateName ) ) as DataTemplate;
                }
                else
                {
                    return base.SelectTemplate( item, container );
                }
            }
        }
    }
}
